package com.estore.network;

import com.estore.Product;
import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Scanner;

public class EStoreClient {
    // 服务器地址和端口号作为成员变量
    private String serverHost = "localhost";
    private int serverPort = 8888;

    public static void main(String[] args) {
        EStoreClient client = new EStoreClient();
        client.start();
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\n=== 电子商城 ===");
            System.out.println("1. 浏览商品");
            System.out.println("2. 退出");
            System.out.print("请选择: ");

            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    browseProducts();
                    break;
                case "2":
                    System.out.println("再见！");
                    return;
                default:
                    System.out.println("无效选择！");
            }
        }
    }

    // 修改browseProducts方法
    private void browseProducts() {
        Socket socket = null;
        try {
            // 创建Socket连接到服务器
            socket = new Socket(serverHost, serverPort);

            // 获取ObjectOutputStream和ObjectInputStream
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 向服务器发送请求字符串"GET_ALL_PRODUCTS"
            output.writeObject("GET_ALL_PRODUCTS");
            output.flush();

            // 从服务器读取响应对象，强制转换为List<Product>
            Object response = input.readObject();

            if (response instanceof List) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;

                // 将获取到的商品列表打印到控制台
                System.out.println("\n=== 商品列表 ===");
                System.out.println("ID\t商品名称\t\t价格\t\t库存");
                System.out.println("----------------------------------------");

                for (Product product : products) {
                    System.out.println(product);
                }

                System.out.println("共 " + products.size() + " 个商品");
            } else {
                System.out.println("服务器返回错误: " + response);
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
        } finally {
            // 确保Socket被关闭
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭Socket时出错: " + e.getMessage());
                }
            }
        }
    }
}